import QtQuick
import QtQuick.LocalStorage
import "./Promise.js" as P

QtObject {
    property var db
    function initDatabase() {
        if (db)
            return;
        db = LocalStorage.openDatabaseSync("moveBox", "1.0", "position", 500);
        db.transaction(tx => {
            tx.executeSql("CREATE TABLE IF NOT EXISTS position(name TEXT,value TEXT)");
        });
    }
    function getValue(key) {
        if (!db)
            initDatabase();
        return getValues([key]).then(v => v[key]);
    }
    /*
        keys : [k1 ,k2 ,k3...]
        return :{k1:v1, k2:v2, k3:v3...}
    */
    function getValues(keys) {
        if (!db)
            initDatabase();
        let res = null;
        const p = new P.Promise(r => res = r);
        const results = {};
        db.transaction(tx => {
            for (let key of keys) {
                const result = tx.executeSql("select * from position where name=?", [key]);
                results[key] = result.rows.length === 1 ? result.rows[0].value : null;
            }
            res(results);
        });
        return p;
    }

    /*
      object:{k1:v1, k2:v2, k3:v3...}
      */
    function setValues(object) {
        let res = null;
        const p = new P.Promise(r => res = r);
        db.transaction(tx => {
            for (let key in object) {
                let value = object[key];
                if ((typeof value === 'object' && value !== null) || Array.isArray(value)) {
                    value = JSON.stringify(value);
                } else if (typeof value === 'number' || typeof value === 'boolean') {
                    value = `${value}`;
                } else if (value === null || value === undefined) {
                    continue;
                }
                const result = tx.executeSql("select * from position where name=?", [key]);
                if (result.rows.length === 1) {
                    tx.executeSql(`update position set value = ? where name = ?`, [value, key]);
                } else {
                    tx.executeSql(`insert into position(name,value) values(?,?)`, [key, value]);
                }
            }
            res(true);
        });
        return p;
    }

    function setValue(key, value) {
        return setValues({
            [key]: value
        });
    }
    Component.onCompleted: {
        initDatabase();
    }
    Component.onDestruction: {}
}
